#include "project.h"


// generate as many passwords as indicated by the
// first (only) argument (i.e. count). Usernames are just 
// integers between 0 and count - 1. In file mypasswd
// we save username, SHA1(password). We also create
// a separate file under each username and store the password
// in plaintext. The latter are used by voters. The
// former is used by CTF.

int
main(int argc, char *argv[])
{
	assert(argc == 2);
	int count = atoi(argv[1]);                 //determines the amount of users that need to be created
	FILE *s = fopen("mypasswd", "w");          //places passwords into a file
	unsigned char passwd[20];                  //maximum length of password characters
	unsigned char hpasswd[SHA_DIGEST_LENGTH];  //using hash table to store password
 /*Based on count, the for loop is generating the user id information*/

	for (int i = 0; i < count; i++){
		BIGNUM *X = NULL, *Y = NULL;
		do {
			if (Y)
				BN_free(Y);
			if (X)
				BN_free(X);
			assert(RAND_bytes(passwd, sizeof(passwd)) == 1);  //asserts a random password 
			assert(SHA1(passwd, sizeof(passwd), hpasswd));    //asserts an encrypted password
			X = BN_bin2bn(passwd, sizeof(passwd), NULL);
			Y = BN_bin2bn(hpasswd, sizeof(hpasswd), NULL);
		} while (BN_num_bytes(X) != 20 || BN_num_bytes(Y) != SHA_DIGEST_LENGTH);
		char *sX = BN_bn2hex(X);
		char *sY = BN_bn2hex(Y);
		char buf[128];                                    //buffer array size
		sprintf(buf, "%d", i);                            //prints the identifer
		FILE *u = fopen(buf, "w");                       //creates a file to store each encrypted password
		fprintf(u, "%s\n", sX);                        //prints the contents of sX(password) to a file
		fclose(u);
		fprintf(s, "%d %s\n", i, sY);             //prints the contents of identifier and sY(hash of password)           
		printf("%d %s %s\n", i, sX, sY);         //prints the contents of identifer, password and encrypted password
		BN_free(X);                              //clear contents of BIGNUM
		BN_free(Y);
		OPENSSL_free(sX);                        //clear contents of OPENSSL
		OPENSSL_free(sY);
	}
	fclose(s);
}
